package com.gjy.disruptor.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.lmax.disruptor.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-08-07 12:16:01
 */
public class ExcelConsumer implements EventHandler<ExcelEntity> {
    private static final Logger log = LoggerFactory.getLogger(ExcelConsumer.class);

    private static final String FILE = "D:\\code\\java\\microservice_spc\\utils-all\\disruptor\\src\\main\\resources\\excel\\";
    private static final Integer SHEET_SIZE = 100000;
    private static final List<ExcelEntity> list = new CopyOnWriteArrayList<>();
    private static final AtomicInteger sheet = new AtomicInteger(0);
    private final ExcelWriter writer = EasyExcel.write(FILE + "disruptor.xlsx").build();

    private final Integer size;
    private final AtomicInteger count = new AtomicInteger(0);

    public ExcelConsumer(Integer size) {
        this.size = size;
    }

    @Override
    public void onEvent(ExcelEntity event, long sequence, boolean endOfBatch) throws Exception {
        list.add(event);
        count.incrementAndGet();
        if (endOfBatch || list.size() >= SHEET_SIZE) {
            log.info("size: {}", list.size());
            WriteSheet s = EasyExcel.writerSheet("Hello" + sheet.getAndIncrement())
                    .head(ExcelEntity.class).build();
            writer.write(list, s);
            list.clear();

            if (count.get() == size) {
                writer.finish();
            }
        }
    }

}
